package com.it.ems.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.it.ems.service.ExpressOrderService;
import com.it.ems.service.UserService;
import com.it.ems.service.RoleService;
import com.it.ems.service.UserRoleService;
import com.it.ems.entity.User;
import com.it.ems.entity.Role;
import com.it.ems.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WebController {

    @Autowired
    private ExpressOrderService expressOrderService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;

    // 定义状态映射：英文 -> 中文，用于前端显示
    private static final Map<String, String> DISPLAY_STATUS_MAP = new HashMap<>();
    static {
        DISPLAY_STATUS_MAP.put("PENDING", "待处理");
        DISPLAY_STATUS_MAP.put("SHIPPED", "已发货");
        DISPLAY_STATUS_MAP.put("PICKED_UP", "已揽收");
        DISPLAY_STATUS_MAP.put("IN_TRANSIT", "运输中");
        DISPLAY_STATUS_MAP.put("UNRECEIVED", "未签收");
        DISPLAY_STATUS_MAP.put("DELIVERED", "已签收");
        DISPLAY_STATUS_MAP.put("CANCELED", "已取消");
    }

    @GetMapping("/login")
    public String login(Model model, String logout, String error) {
        if (logout != null) {
            model.addAttribute("message", "您已成功退出登录");
        }
        if (error != null) {
            model.addAttribute("error", "用户名或密码错误");
        }
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String handleRegister(@RequestParam String username,
                                @RequestParam String password,
                                @RequestParam String confirmPassword, 
                                @RequestParam String realName,
                                @RequestParam String phoneNumber,
                                @RequestParam(required = false) String email,
                                RedirectAttributes redirectAttributes) {
        try {
            // 验证输入
            if (username == null || username.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "用户名不能为空");
                return "redirect:/register";
            }
            
            if (password == null || password.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "密码不能为空");
                return "redirect:/register";
            }
            
            if (!password.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的密码不一致");
                return "redirect:/register";
            }
            
            if (realName == null || realName.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "真实姓名不能为空");
                return "redirect:/register";
            }
            
            if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "手机号码不能为空");
                return "redirect:/register";
            }
            
            // 简单的手机号格式验证
            if (!phoneNumber.matches("^1[3-9]\\d{9}$")) {
                redirectAttributes.addFlashAttribute("error", "请输入正确的手机号码格式");
                return "redirect:/register";
            }
            
            // 检查用户名是否已存在
            if (userService.findByUsername(username.trim()) != null) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在，请选择其他用户名");
                return "redirect:/register";
            }
            
            // 检查手机号是否已存在
            if (userService.findByPhone(phoneNumber.trim()) != null) {
                redirectAttributes.addFlashAttribute("error", "手机号码已被使用，请使用其他手机号码");
                return "redirect:/register";
            }
            
            // 创建用户对象
            User user = new User();
            user.setUsername(username.trim());
            user.setPassword(password); // UserService会处理密码加密
            user.setRealName(realName.trim());
            user.setPhoneNumber(phoneNumber.trim());
            if (email != null && !email.trim().isEmpty()) {
                user.setEmail(email.trim());
            }
            
            // 保存用户
            userService.save(user);
            
            // 为新用户分配默认角色（普通用户）
            Role userRole = roleService.findByName("ROLE_USER");
            if (userRole != null) {
                UserRole userRoleRelation = new UserRole();
                userRoleRelation.setUserId(user.getId());
                userRoleRelation.setRoleId(userRole.getId());
                userRoleService.save(userRoleRelation);
            }
            
            redirectAttributes.addFlashAttribute("message", "注册成功！请使用您的用户名和密码登录");
            return "redirect:/login";
            
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败：" + e.getMessage());
            return "redirect:/register";
        }
    }

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        model.addAttribute("todayOrders", expressOrderService.countTodayOrders());
        model.addAttribute("pendingPackages", expressOrderService.countOrdersByStatus("PENDING"));
        model.addAttribute("inTransitPackages", expressOrderService.countOrdersByStatus("IN_TRANSIT"));
        model.addAttribute("deliveredPackages", expressOrderService.countOrdersByStatus("DELIVERED"));

        List<com.it.ems.entity.ExpressOrder> recentOrders = expressOrderService.findRecentOrders(5);
        model.addAttribute("recentOrders", recentOrders);
        model.addAttribute("displayStatusMap", DISPLAY_STATUS_MAP); // 添加映射到模型
        return "dashboard";
    }

    @GetMapping("/")
    public String home() {
        return "redirect:/dashboard";
    }
} 